jQuery(function() {
	
	// global vars used in most funcitons
	var userId = "";
	var fitIds = new Array(); 
	var fitId;
	var fitIndex = 0;
	var fitParamFlag = false;
	var numFits;
	var numImages;
	var imgIndex = 0;	
	
	if ($.getUrlVar('fitid')) {
		fitParamFlag = true;
		fitId = $.getUrlVar('fitid')
		userId = getUserIdFromFitId(fitId);

		populateUser();
		fitIndexFinder();
		populateFit();
	} else {
		if ($.getUrlVar('userid')) {
			userId = $.getUrlVar('userid');
			populateUser();
			populateFit();		
		} else {
			$.getJSON("/noassertions/access/user/random?userid=" + userId + "&nocache=" + new Date().getTime(),
					function(json) {
				userId = json.users[0].userid;
				populateUser();
				populateFit();		
			});
		}
	}

	// Random Rider link (same as loading without userid or fitid param)
	$("#nextrandom").click(function() {
		$.getJSON("/noassertions/access/user/random?userid=" + userId + "&nocache=" + new Date().getTime(),
				function(json) {
			userId = json.users[0].userid;
			fitIndex = 0;
			populateUser();
			populateFit();
		});
		return false;
	});

	
	// Control stuff
	$("#prevfit").click(function() {getPrevFit(); return false;});
	$("#nextfit").click(function() {getNextFit(); return false;});

	$("#previmg").click(function() {getPrevImg(); return false;});
	$("#nextimg").click(function() {getNextImg(); return false;});
	
	$("#submitbutton").click(processComment);
	
	// Functions that control the DOM manipulation
	function populateUser() {
		$.getJSON("/noassertions/access/rider/" + userId,
				function(json) {
			$("#totalbodyheight").html(json.riders[0].totalbodyheight);
			$("#sternalnotch").html(json.riders[0].sternalnotch);
			$("#shoulderwidth").html(json.riders[0].shoulderwidth);
			$("#trunk").html(json.riders[0].trunk);
			$("#humerus").html(json.riders[0].humerus);
			$("#forearm").html(json.riders[0].forearm);
			$("#totalarm").html(json.riders[0].totalarm);
			$("#femur").html(json.riders[0].femur);
			$("#tibia").html(json.riders[0].tibia);
			$("#inseam").html(json.riders[0].inseam);
			$("#footlength").html(json.riders[0].footlength);
			if (json.riders[0].notes != "") {
				$("#ridernotes").html(json.riders[0].notes);
			} else {
				$("#ridernotes").html('No notes associated with this rider');
			}
			$("#similarrider").attr("href", '/noassertions/access/similar/rider/' + userId);
		});
		
		$.getJSON("/noassertions/access/user/" + userId,
				function(json) {
			$("#firstname").html(json.users[0].firstname);
			$("#lastname").html(json.users[0].lastname);	
			$("#birthdate").html(json.users[0].birthdate);
		});
	}
	
	function populateFit() {
		$.getJSON("/noassertions/access/fit/" + userId,
				function(json) {
			numFits = 0;
			numImages = 0;
			imgIndex = 0;
			$.each(json.fits, function(i,fit) {
				numFits++;
				fitIds[i] = fit.fitid; 
			});
			if (fitParamFlag) {fitIndexFinder(); fitParamFlag = false;} else {fitId = fitIds[fitIndex];}

			$("#dateofmeasurement").html(json.fits[fitIndex].dateofmeasurement);
			$("#saddleheight").html(json.fits[fitIndex].saddleheight);
			$("#centertobars").html(json.fits[fitIndex].centertobars);
			$("#centertosaddle").html(json.fits[fitIndex].centertosaddle);
			$("#floortosaddle").html(json.fits[fitIndex].floortosaddle);
			$("#floortobars").html(json.fits[fitIndex].floortobars);
			$("#barswidth").html(json.fits[fitIndex].barswidth);
			if (json.fits[fitIndex].notes != "") {
				$("#fitnotes").html(json.fits[fitIndex].notes);
			} else {
				$("#fitnotes").html('No notes associated with this fit');
			}		
			$("#frame").html(json.fits[fitIndex].frame);
			$("#shifters").html(json.fits[fitIndex].shifters);
			$("#saddle").html(json.fits[fitIndex].saddle);
			$("#pedals").html(json.fits[fitIndex].pedals);
			$("#stem").html(json.fits[fitIndex].stem);
			$("#bars").html(json.fits[fitIndex].bars);
			$("#post").html(json.fits[fitIndex].post);
			$("#cranks").html(json.fits[fitIndex].cranks);
			
			$("#similarfit").attr("href", '/noassertions/access/similar/fit/' + fitId);
			
			populateComment();
			populateImage();
		});
	}
	
	function populateFitControl() {
		$("#currentFit").html(fitIndex+1);
		$("#numFits").html(numFits);		

		if (numImages == 1) {$("#nextimg").css({opacity : '.5', filter : 'alpha(opacity = 50);'}); $("a#nextimglink").removeAttr("href");}
		if (numFits == 1) {$("#nextfit").css({opacity : '.5', filter : 'alpha(opacity = 50);'}); $("a#nextfitlink").removeAttr("href");}
		
		if (fitIndex+1 < numFits) {$("#nextfit").css({opacity : '1', filter : 'alpha(opacity = 100);'}); $("a#nextfitlink").attr("href", "");}
		  else {$("#nextfit").css({opacity : '.5', filter : 'alpha(opacity = 50);'}); $("a#nextfitlink").removeAttr("href");}
		if (fitIndex > 0) {$("#prevfit").css({opacity : '1', filter : 'alpha(opacity = 100);'}); $("a#prevfitlink").attr("href", "");}
		  else {$("#prevfit").css({opacity : '.5', filter : 'alpha(opacity = 50);'}); $("a#prevfitlink").removeAttr("href");}
		
		if (imgIndex+1 < numImages) {$("#nextimg").css({opacity : '1', filter : 'alpha(opacity = 100);'}); $("a#nextimglink").attr("href", "");}
		  else {$("#nextimg").css({opacity : '.5', filter : 'alpha(opacity = 50);'}); $("a#nextimglink").removeAttr("href");}
		if (imgIndex > 0) {$("#previmg").css({opacity : '1', filter : 'alpha(opacity = 100);'}); $("a#previmglink").attr("href", "");}
		  else {$("#previmg").css({opacity : '.5', filter : 'alpha(opacity = 50);'}); $("a#previmglink").removeAttr("href");}
	}
	
	function populateComment() {	
		$("#commentslist").html("");
		$.getJSON("/noassertions/access/comment/" + fitId,
				function(json) {
			if (json.comments.length != 0) {
				$.each(json.comments, function(i,comment) {
					$("#commentslist").append('<li>On ' + comment.commentcreated + ', ' + comment.commenter + ' said: <p>' + comment.comment + '</p></li>');
				});
			} else {
				$("#commentslist").append('<li>No one has commented on this fit yet. Be the first to comment by using the comment box below.</li>'); 
			}
		});
	}
	
	function populateImage() {
		$.getJSON("/noassertions/access/image/" + fitId,
			function(json) {
				numImages = json.images.length;
				$("#displayedimage").html('<a href="/noassertions/fitimages/' + json.images[imgIndex].filename + '" target="_blank"><img src="/noassertions/fitimages/s_' + json.images[imgIndex].filename + '"></img></a>');
				$("#imagelabel").html(json.images[imgIndex].label);
				populateFitControl();
			});
	}
	
	// Helper functions for keeping track of indexes
	function getNextFit() {
		if (fitIndex+1 < numFits) {
			fitIndex++;
			populateFit();
		}	
	}

	function getPrevFit() {
		if (fitIndex > 0) {
			fitIndex--;
			populateFit();
		}
	}
	
	function getNextImg() {
		if (imgIndex+1 < numImages) {
			imgIndex++;
			populateImage();
		}	
	}

	function getPrevImg() {
		if (imgIndex > 0) {
			imgIndex--;
			populateImage();
		}
	}
	
	// AJAX comment post handler
	function processComment() {
		var dataString = 'fitid=' + fitId + '&comment=' + $("textarea#comment").val() + '&commenter=' + $("#emailaddress").text();
		$.ajax({
			type: "POST",
			url: "/noassertions/access/comment",
			data: dataString,
			success: function() {
				var commentFade = $('<li>You recently posted: <p>' + $("textarea#comment").val() + '</p></li>').hide();
				$('#commentslist').prepend(commentFade);
				commentFade.fadeIn(2000);
				$("textarea#comment").val('');
			}
		});
		return false;
	}
	
	// Utility functions
	function getUserIdFromFitId(fitId) {
		$.ajax({
		    type: 'GET',
		    url: '/noassertions/access/fit/userfromfit/' + fitId,
		    dataType: 'json',
		    success: function(json) {userId = json.userid;},
		    data: {},
		    async: false
		});
		return userId;
	}
	
	function fitIndexFinder() {
		$.each(fitIds, function(i,id) {
			if (fitId == id){
				fitIndex = i;
			}
		});
		
	}

	// IE 6 and 7 opacity business
	if($.browser.msie && $.browser.version=="6.0" || $.browser.msie && $.browser.version=="7.0") {
		$("#nextfit").attr("src", "/noassertions/img/resultset_next_ie6.png");
		$("#prevfit").attr("src", "/noassertions/img/resultset_previous_ie6.png");
		$("#nextimg").attr("src", "/noassertions/img/resultset_next_ie6.png");
		$("#previmg").attr("src", "/noassertions/img/resultset_previous_ie6.png");
	}
});

// Helps us find params in request URL
// Taken directly from http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html
$.extend({
	getUrlVars: function(){
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	for(var i = 0; i < hashes.length; i++)
	{
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
	return vars;
},
getUrlVar: function(name){
	return $.getUrlVars()[name];
}
});